from django.shortcuts import render

# Create your views here.

# 请求方式 GET /goods/categories/(?P<category_id>\d+)/hotskus/
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import Goods, GoodsCategory, SKU
from goods.serializer import GoodsCategorySerializer, SKUListSerializer, HotsSkuSerializer

import time
import os
from goods.models import GoodsChannel
from contents.models import ContentCategory
from collections import OrderedDict
from django.template import loader
from django.conf import settings

from utils.paginations import MyPageNumberPagination


class IndexAPIView(APIView):

    def get(self,request):
        # 初始化存储容器
        categories = OrderedDict()
        # 获取一级分类
        channels = GoodsChannel.objects.order_by('group_id', 'sequence')

        # 对一级分类进行遍历
        for channel in channels:
            # 获取group_id
            group_id = channel.group_id
            # 判断group_id 是否在存储容器,如果不在就初始化
            if group_id not in categories:
                categories[group_id] = {
                    'channels': [],
                    'sub_cats': []
                }

            one = channel.category
            # 为channels填充数据
            categories[group_id]['channels'].append({
                'id': one.id,
                'name': one.name,
                'url': channel.url
            })
            # 为sub_cats填充数据
            for two in one.goodscategory_set.all():
                # 初始化 容器
                two.sub_cats = []
                # 遍历获取
                for three in two.goodscategory_set.all():
                    two.sub_cats.append(three)

                # 组织数据
                categories[group_id]['sub_cats'].append(two)

        # 广告和首页数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        # content_categories = [{'name':xx , 'key': 'index_new'}, {}, {}]
        # {
        #    'index_new': [] ,
        #    'index_lbt': []
        # }
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
        print(2222)
        context = {
            'categories': categories,
            'contents': contents
        }

        return render(request,'index.html',context)


# class GoodsDetailAPIView(APIView):
#     def get(self,request,pk):
#         try:
#             goodsCategory=GoodsCategory.objects.get(id=pk)
#         except GoodsCategory.DoesNotExist:
#             return Response(status=status.HTTP_400_BAD_REQUEST)
#
#         serializer=GoodsCategorySerializer(goodsCategory)
#
#         return Response(serializer.data)
# class SKUListAPIView(APIView):
#     def get(self,request,pk):
#         order=request.query_params.get('ordering')
#         page=int(request.query_params.get('page'))
#         page_size=int(request.query_params.get('page_size'))
#         start=(page-1)*page_size
#         end=page*page_size
#         length=len(SKU.objects.filter(category_id=pk))
#         if  length < start:
#             return Response({'message': '到头了'})
#         print(len(SKU.objects.filter(category_id=pk)))
#         # if end > SKU.objects.filter(category_id=pk).count():
#         skus=SKU.objects.filter(category_id=pk).order_by(order)[start:end]
#
#         if skus is None:
#             return Response({'message':'没有分类数据'},status=status.HTTP_400_BAD_REQUEST)
#         serializer=SKUListSerializer(skus,many=True)
#         return Response(serializer.data)


# GET /goods/categories/(?P<category_id>\d+)/hotskus/
from rest_framework_extensions.cache.mixins import ListCacheResponseMixin
from rest_framework.generics import ListAPIView
class HotsSkuAPIView(ListCacheResponseMixin,ListAPIView):
    # 分页类(不用全局分页)
    pagination_class = None
    serializer_class = HotsSkuSerializer

    def get_queryset(self):
        category_id=self.kwargs.get('category_id')
        queryset=SKU.objects.filter(category_id=category_id,is_launched=True).order_by('-sales')[0:2]
        return queryset

# GET /goods/categories/(?P<category_id>\d+)/skus/?page=xxx&page_size=xxx&ordering=xxx
from rest_framework.filters import OrderingFilter
class SKUListAPIView(ListAPIView):
    '''
    商品列表数据
    '''
    # 局部分页
    # pagination_class = MyPageNumberPagination
    # 排序
    filter_backends = [OrderingFilter]
    ordering_fields=('create_time','price','sales')

    serializer_class = SKUListSerializer
    def get_queryset(self):
        category_id=self.kwargs['category_id']
        queryset=SKU.objects.filter(category_id=category_id,is_launched=True)
        return queryset
    # 设置了全局分页
from .serializer import SKUIndexSerializer
from drf_haystack.viewsets import HaystackViewSet

class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """

    index_models = [SKU]

    serializer_class = SKUIndexSerializer